import request from '@/utils/request'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// ============================================
// 配置与工具函数
// ============================================

// 开发环境日志开关
const isDev = process.env.NODE_ENV === 'development'

// 统一日志工具
const logger = {
  info: (title, ...args) => {
    if (isDev) Logger.log(`[Agg API] ${title}`, ...args)
  },
  error: (title, ...args) => {
    if (isDev) Logger.error(`[Agg API Error] ${title}`, ...args)
  },
  warn: (title, ...args) => {
    if (isDev) Logger.warn(`[Agg API Warn] ${title}`, ...args)
  }
}

// 创建聚合系统专用的axios实例
const aggregationService = axios.create({
  baseURL: '',  // 空字符串，直接使用 /agg 路径，由vue.config.js中的代理处理
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器 - 自动添加token
aggregationService.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers = config.headers || {}
      config.headers['token'] = token
    }
    logger.info('Request:', config.method.toUpperCase(), config.url, { params: config.params, data: config.data })
    return config
  },
  error => {
    logger.error('Request Error:', error.message)
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误并简化返回值
aggregationService.interceptors.response.use(
  response => {
    logger.info('Response Success:', response.config.url, { status: response.status, data: response.data })
    // 直接返回 data，简化调用方使用
    return response.data
  },
  error => {
    logger.error('Response Error:', error.config?.url, {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message
    })

    if (error.response?.status === 401) {
      // token过期，可以在这里添加清除token和跳转登录的逻辑
      logger.warn('Token expired, please login again')
    }
    return Promise.reject(error)
  }
)

// 通用请求方法
const createRequest = (url, method = 'get', options = {}) => {
  return (paramsOrData) => {
    const config = {
      url,
      method,
      ...options
    }

    // 根据方法类型决定使用params还是data
    if (method.toLowerCase() === 'get' || method.toLowerCase() === 'delete') {
      config.params = paramsOrData
    } else {
      // POST, PUT等使用data，除非明确指定使用params
      if (options.useParams) {
        config.params = paramsOrData
      } else {
        config.data = paramsOrData
      }
    }

    return aggregationService(config)
  }
}

// ============================================
// 用户认证相关接口
// ============================================

// 聚合登录接口（web端）
export const aggregationLogin = createRequest('/agg/user/login', 'post')

// APP用户登录
export const appLogin = createRequest('/agg/user/appLogin', 'post')

// 用户退出登录
export const logout = createRequest('/agg/user/loginOut', 'post', { useParams: true })

// 忘记密码
export const forgetPassword = createRequest('/agg/user/forget', 'post')

// 重置密码
export const resetPassword = createRequest('/agg/user/reset', 'post')

// 发送短信验证码
export const sendSmsCode = createRequest('/agg/sms/sendCode', 'get')

// 验证短信验证码
export const validateSmsCode = (phone, code) => {
  return aggregationService({
    url: '/sms/validate',
    method: 'post',
    params: { phone, code }
  })
}

// ============================================
// 用户管理相关接口
// ============================================

// 获取当前登录用户信息
export const getCurrentUser = createRequest('/agg/user/current', 'get')

// 获取用户信息（支持传id或获取当前用户）
export const getUserInfo = createRequest('/agg/user/getUserInfo', 'get')

// 更新用户信息
export const updateUserInfo = createRequest('/agg/user/edit', 'post')

// 删除用户（通用接口）
export const deleteUser = createRequest('/agg/user/delete', 'get')

// ============================================
// 分佣比例相关接口
// ============================================

// 获取所有用户分润比例配置信息（支持分页和条件查询）
export const getUserProfitList = (params) => {
  // 提取 query 参数
  const { pageIndex, pageSize, keyword, userType, useCustomConfig } = params || {}

  // 构建 query 参数
  const queryParams = {}
  if (keyword) {
    queryParams.keyword = keyword  // 搜索关键词：支持姓名模糊搜索、业务员编号精确搜索、手机号精确搜索
  }
  if (userType !== null && userType !== undefined && userType !== '') {
    queryParams.userType = userType
  }
  if (useCustomConfig !== null && useCustomConfig !== undefined && useCustomConfig !== '') {
    queryParams.useCustomConfig = useCustomConfig
  }

  // 构建 body 参数
  const bodyParams = {
    pageIndex: pageIndex || 1,
    pageSize: pageSize || 10
  }

  return aggregationService({
    url: '/agg/userProfit/list',
    method: 'post',
    params: queryParams,
    data: bodyParams
  })
}

// 修改特定用户分润比例
export const editUserProfit = createRequest('/agg/userProfit/saveConfig', 'post')

// 获取角色统一分佣比例配置信息
export const getProportionInfo = createRequest('/agg/proportion/getInfo', 'get')
// 修改角色统一分拥比例
export const editProportion = createRequest('/agg/proportion/batchEdit', 'post')


// ============================================
// 商家审核相关接口
// ============================================

// 分页查询商家审核
export const getMerchantAuditPage = createRequest('/agg/merchantAudit/page', 'post')

// 审核商家
export function checkMerchantAudit(data) {
  return aggregationService({
    url: '/agg/merchantAudit/check',
    method: 'post',
    params: {
      id: data.id,
      statue: data.statue,
      reason: data.reason || ''
    }
  })
}

// 查看商家审核详情
export const getMerchantAuditDetail = createRequest('/agg/merchantAudit/getInfo', 'get')

// 添加商家审核
export const addMerchantAudit = createRequest('/agg/merchantAudit/add', 'post')

// 编辑商家审核
export const editMerchantAudit = createRequest('/agg/merchantAudit/edit', 'post')

// 获取商家审核统计（待审核数量）
export function getMerchantAuditCount() {
  return getMerchantAuditPage({
    pageIndex: 1,
    pageSize: 1,
    statue: 1 // 1=待审核
  })
}

// ============================================
// 订单管理相关接口
// ============================================

// 查询订单列表（已废弃/agg/order/page，统一使用/agg/order/list）
export const getOrderPage = createRequest('/agg/order/list', 'post')

// 查询订单列表（订单导出使用）
export const getOrderList = createRequest('/agg/order/list', 'post')

// 查询订单详情
export const getOrderDetail = createRequest('/agg/order/getInfo', 'get')

// 创建订单
export const createOrder = createRequest('/agg/order/create', 'post')

// 最近订单
export const getRecentOrders = createRequest('/agg/order/list', 'post')

// ============================================
// 提现管理相关接口
// ============================================

// 分页查询提现列表
export const getWithdrawPage = createRequest('/agg/withdraw/page', 'post')

// 查询提现详情
export const getWithdrawDetail = createRequest('/agg/withdraw/getInfo', 'get')

// 提现审核
export const checkWithdraw = createRequest('/agg/withdraw/check', 'post', { useParams: true })

// 添加提现申请
export const addWithdraw = createRequest('/agg/withdraw/add', 'post', { useParams: true })

// 获取提现审核统计（待审核数量）
export function getWithdrawAuditCount() {
  return getWithdrawPage({
    pageIndex: 1,
    pageSize: 1,
    statue: 1 // 1=待审核
  })
}

// 区域代理提现
export const agentWithdraw = createRequest('/agg/withdraw/add', 'post', { useParams: true })

// 获取区域代理可提现金额和收益记录
export const getAgentWithdrawInfo = createRequest('/agg/withdraw/agentInfo', 'get')

// 提交提现申请
export const submitAgentWithdraw = createRequest('/agg/withdraw/submit', 'post')

// 获取提现记录
export const getAgentWithdrawRecords = createRequest('/agg/withdraw/records', 'post')

// ============================================
// 银行卡管理相关接口
// ============================================

// 新增银行卡
export const addBankCard = createRequest('/agg/card/add', 'post')

// 编辑银行卡
export const editBankCard = createRequest('/agg/card/edit', 'post')

// 获取当前登录用户银行卡信息
export const getCurrentCard = createRequest('/agg/card/current', 'get')

// 银行卡详情（支持传userId或获取当前用户）
export const getBankCardDetail = createRequest('/agg/card/getInfo', 'get')

// ============================================
// 业务员管理相关接口
// ============================================

// 分页查询业务员
export const getSalesmanPage = createRequest('/agg/user/saleManPage', 'post')

// 查询业务员列表（分页）
export const getSalesmanList = createRequest('/agg/user/saleManPage', 'post')

// 添加业务员
export const addSalesman = createRequest('/agg/user/addSaleMan', 'post')

// 编辑业务员
export const editSalesman = createRequest('/agg/user/edit', 'post')

// 查看业务员详情
export const getSalesmanDetail = createRequest('/agg/user/getUserInfo', 'get')

// 删除业务员
export const deleteSalesman = createRequest('/agg/user/delete', 'get')

// 区域代理直接添加业务员（无需审核）
export const addSalesmanByAgent = createRequest('/agg/user/addSalesmanByAgent', 'post')

// ============================================
// 业务员审核相关接口
// ============================================

// 提交业务员审核申请
export const submitSalesmanAudit = createRequest('/agg/salesmanAudit/add', 'post')

// 查询业务员审核列表（分页）
export const getSalesmanAuditPage = createRequest('/agg/salesmanAudit/page', 'post')

// 审核业务员（通过/拒绝）
export function checkSalesmanAudit(data) {
  return aggregationService({
    url: '/agg/salesmanAudit/check',
    method: 'post',
    params: {
      id: data.id,
      statue: data.statue,
      reason: data.reason || ''
    }
  })
}

// 查看业务员审核详情
export const getSalesmanAuditDetail = createRequest('/agg/salesmanAudit/getInfo', 'get')

// 删除业务员审核记录
export const deleteSalesmanAudit = createRequest('/agg/salesmanAudit/delete', 'post', { useParams: true })

// ============================================
// 商家管理相关接口
// ============================================

// 分页查询商家
export const getMerchantPage = createRequest('/agg/user/merchantPage', 'post')

// 查询商家列表（分页）
export const getMerchantList = createRequest('/agg/user/merchantPage', 'post')

// 查看商家详情
export const getMerchantDetail = createRequest('/agg/merchant/getInfo', 'get')

// 编辑商家
export const editMerchant = createRequest('/agg/user/edit', 'post')

// 更新商家信息
export const updateMerchant = createRequest('/agg/user/edit', 'post')

// 更新锁定用户数量
export const updateLockNum = createRequest('/agg/user/updateLockNum', 'post')

// ============================================
// 区域代理相关接口
// ============================================

// 获取区域代理统计数据
export const getAgentStatistics = createRequest('/agg/statistics/home', 'get')

// 获取区域代理最近订单
export function getAgentRecentOrders() {
  return getOrderList({ pageIndex: 1, pageSize: 5 })
}

// 分页查询区域代理下的商家
export const getAgentMerchantPage = createRequest('/agg/user/merchantPage', 'post')

// 分页查询区域代理下的业务员
export const getAgentSalesmanPage = createRequest('/agg/user/saleManPage', 'post')

// 分页查询区域代理订单
export const getAgentOrderPage = createRequest('/agg/order/list', 'post')

// 区域代理统计数据
export const getAgentDashboardStats = createRequest('/agg/statistics/agentDashboard', 'get')

// ============================================
// 区域代理管理相关接口
// ============================================

// 分页查询区域代理
export const getRegionAgentPage = createRequest('/agg/user/regionPage', 'post')

// 查询区域代理详情
export const getRegionAgentDetail = createRequest('/agg/user/getUserInfo', 'get')

// 添加区域代理
export const addRegionAgent = createRequest('/agg/user/addRegion', 'post')

// 编辑区域代理
export const editRegionAgent = createRequest('/agg/user/edit', 'post')

// 获取区域列表
export function getRegionList() {
  return getRegionAgentPage({
    pageIndex: 1,
    pageSize: 100
  })
}

// ============================================
// 聚合码管理相关接口
// ============================================

// 生成聚合二维码
export const generateQrCode = createRequest('/agg/qrcode/generate', 'get')

// 生成下载二维码
export const generateDownloadQrCode = createRequest('/agg/qrcode/download', 'get')

// 处理二维码扫描
export const handleQrScan = createRequest('/agg/qrcode/scan', 'get')

// 聚合码分页列表
export const getQrCodePage = createRequest('/agg/qrcode/page', 'get')

// 聚合码详情
export const getQrCodeDetail = createRequest('/agg/qrcode/detail', 'get')

// ============================================
// 账户管理相关接口
// ============================================

// 获取当前登录用户账户信息
export const getCurrentAccount = createRequest('/agg/account/current', 'get')

// 账户详情（支持传userId或获取当前用户）
export const getAccountInfo = createRequest('/agg/account/getInfo', 'get')

// 获取所有账户列表（分页）
export const getAccountList = createRequest('/agg/account/page', 'post')

// ============================================
// 统计数据相关接口
// ============================================

// 首页统计数据
export const getHomeStatistics = createRequest('/agg/statistics/home', 'get')

// 贡献数据
export const getContributionData = createRequest('/agg/statistics/contribution', 'get')

// ============================================
// 定时任务管理相关接口
// ============================================

// 获取定时任务列表
export const getScheduledJobList = createRequest('/agg/job/page', 'post')

// 获取历史执行日志
export const getHistoryLog = createRequest('/agg/jobLog/listByJobId', 'get')

// 启动定时任务
export const startScheduledJob = createRequest('/agg/job/start', 'post', { useParams: true })

// 停止定时任务
export const stopScheduledJob = createRequest('/agg/job/stop', 'post', { useParams: true })

// 立即执行定时任务
export const runScheduledJob = createRequest('/agg/job/run', 'post', { useParams: true })

// ============================================
// 商品轮播管理相关接口
// ============================================

// 获取轮播列表
export const getCarouselList = createRequest('/agg/product/carouselList', 'get')

// 标记/取消商品为轮播图
export const markCarousel = createRequest('/agg/product/markCarousel', 'post')

// 更新轮播排序
export const updateCarouselSort = createRequest('/agg/product/updateCarouselSort', 'post')

// 获取所有商品列表（用于轮播选择）
export const getAllProductList = createRequest('/agg/product/page', 'post')

// ============================================
// 导出服务实例
// ============================================

export { aggregationService }
